import { Toast } from 'antd-mobile'
import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import http from '../../api'
import Loading from '../../components/publicComponents/Loading'
import PubNav from '../../components/publicComponents/pubNav'
import { AddressType } from '../../myTypes'
import style from './userAddress.module.css'

export default function UserAddress() {
  const navigate = useNavigate()
  let [userId, setUserId] = useState('')
  const [allAddressList, setAllAddressList] = useState<Array<AddressType>>([])

  useEffect(() => {
    const id = localStorage.getItem('userId')
    if (id) {
      userId = id
      getAllAddress()
      setUserId(id)
    } else {
      navigate('/login')
    }
  }, [])

  async function getAllAddress() {
    Toast.show({
      content: '加载中...',
      maskClickable: false,
      duration: 0,
      icon: <Loading />
    })
    const data = await http('get', '/mty/shippingAddress/getAll', {
      userId
    })
    Toast.clear()
    if (data) {
      const addressList = data.data as Array<AddressType>
      setAllAddressList([...addressList])
    }
  }

  return (
    <div style={{ paddingTop: '46px', minHeight: '100vh', backgroundColor: '#fff', paddingBottom: '50px' }}>
      <PubNav title="收货地址" />
      <div className={style['address-list']}>
        {allAddressList.map((item) => (
          <div className={style['address-item']} key={item.id}>
            <div className={style['normal']}>
              {item.status === 1 && <div className={style['is-normal']}>默认</div>}

              <div className={style['tag']}>{item.type === 0 ? '家' : item.type === 1 ? '公司' : ' 学校'}</div>
            </div>
            <div className={style['address']}>{item.province + item.city + item.area}</div>
            <div className={style['user-info']}>
              <div className={style['name']}>{item.name}</div>
              <div className={style['mobile']}>{item.tel}</div>
              <div
                className={style['edit']}
                onClick={() => {
                  navigate('/address/add', {
                    state: {
                      id: item.id,
                      item
                    }
                  })
                }}
              >
                <div className={style['edit-icon']}>
                  <img src="/static/user/icon-edit-9e9.png" alt="" />
                </div>
                <div className={style['text']}>编辑</div>
              </div>
            </div>
          </div>
        ))}
      </div>
      <div
        className={style['add-address']}
        onClick={() => {
          navigate('/address/add')
        }}
      >
        添加新地址
      </div>
    </div>
  )
}
